<template>
  <div class="company-container">
    <n-card title="公司管理" :bordered="false">
      <!-- 操作栏 -->
      <n-space justify="space-between" style="margin-bottom: 16px">
        <n-space>
          <n-input
            v-model:value="searchText"
            placeholder="搜索公司名称"
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <n-icon>
                <SearchOutline />
              </n-icon>
            </template>
          </n-input>
          <n-button @click="handleSearch" type="primary">
            搜索
          </n-button>
        </n-space>
        <n-button @click="handleAdd" type="primary">
          <template #icon>
            <n-icon>
              <AddOutline />
            </n-icon>
          </template>
          添加公司
        </n-button>
      </n-space>

      <!-- 公司表格 -->
      <n-data-table
        :columns="columns"
        :data="filteredData"
        :loading="loading"
        :pagination="pagination"
        :row-key="rowKey"
        @update:checked-row-keys="handleCheck"
        @update:page="handlePageChange"
      />

      <!-- 添加/编辑公司对话框 -->
      <n-modal
        v-model:show="showModal"
        :title="formTitle"
        preset="card"
        style="width: 500px"
      >
        <n-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-placement="left"
          label-width="80"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="公司名称" path="company">
            <n-input
              v-model:value="formData.company"
              placeholder="请输入公司名称"
            />
          </n-form-item>
          <n-space justify="end">
            <n-button @click="showModal = false">取消</n-button>
            <n-button type="primary" @click="submitForm">确定</n-button>
          </n-space>
        </n-form>
      </n-modal>

      <!-- 删除确认对话框 -->
      <delete-confirm-dialog
        v-model:show="showDeleteModal"
        :content="`确定要删除公司「${companyToDelete?.company || ''}」吗？此操作不可恢复。`"
        @confirm="handleDeleteConfirm"
      />
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, h, onMounted } from 'vue';
import { 
  NSpace, 
  NButton, 
  NInput, 
  NIcon, 
  NCard, 
  NDataTable, 
  NModal, 
  NForm, 
  NFormItem, 
  useMessage
} from 'naive-ui';
import { 
  SearchOutline, 
  AddOutline, 
  TrashOutline, 
  CreateOutline
} from '@vicons/ionicons5';
import { companyApi } from '../api';
// import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';

// 消息提示
const message = useMessage();

// 搜索
const searchText = ref('');
const loading = ref(false);

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageSizes: [10, 20, 30, 40],
  showSizePicker: true,
  prefix({ itemCount }) {
    return `总共 ${itemCount} 条数据`;
  }
});

// 公司数据
const companyData = ref([]);

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchText.value) return companyData.value;
  return companyData.value.filter(item => 
    item.company.includes(searchText.value)
  );
});

// 表格列定义
const columns = [
  {
    title: 'ID',
    key: 'company_id',
    width: 80
  },
  {
    title: '公司名称',
    key: 'company'
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render(row) {
      return h(
        NSpace,
        { justify: 'center' },
        {
          default: () => [
            h(
              NButton,
              {
                tertiary: true,
                size: 'small',
                type: 'info',
                onClick: () => handleEdit(row)
              },
              { icon: () => h(NIcon, null, { default: () => h(CreateOutline) }) }
            ),
            h(
              NButton,
              {
                tertiary: true,
                size: 'small',
                type: 'error',
                onClick: () => handleDelete(row)
              },
              { icon: () => h(NIcon, null, { default: () => h(TrashOutline) }) }
            )
          ]
        }
      );
    }
  }
];

// 行key
const rowKey = (row) => row.company_id;
const checkedRowKeys = ref([]);

// 表单相关
const formRef = ref(null);
const showModal = ref(false);
const formMode = ref('add'); // 'add' 或 'edit'
const formData = ref({
  company_id: null,
  company: ''
});

// 表单标题
const formTitle = computed(() => {
  return formMode.value === 'add' ? '添加公司' : '编辑公司';
});

// 表单验证规则
const rules = {
  company: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ]
};

// 删除相关
const showDeleteModal = ref(false);
const companyToDelete = ref(null);

// 初始化获取公司数据
const fetchCompanyData = async () => {
  loading.value = true;
  try {
    // 实际项目中应从API获取
    // const res = await companyApi.getCompanyList({
    //   page: pagination.page,
    //   pageSize: pagination.pageSize
    // });
    // companyData.value = res.data;
    // pagination.itemCount = res.total;
    
    // 模拟数据
    companyData.value = [
      {
        company_id: 1,
        company: '公司1'
      },
      {
        company_id: 2,
        company: '公司2'
      }
    ];
    pagination.itemCount = companyData.value.length;
  } catch (error) {
    console.error('获取公司数据失败:', error);
    message.error('获取公司数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchCompanyData();
};

// 添加公司
const handleAdd = () => {
  formMode.value = 'add';
  formData.value = {
    company_id: null,
    company: ''
  };
  showModal.value = true;
};

// 编辑公司
const handleEdit = (row) => {
  formMode.value = 'edit';
  formData.value = { ...row };
  showModal.value = true;
};

// 删除公司
const handleDelete = (row) => {
  companyToDelete.value = row;
  showDeleteModal.value = true;
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        if (formMode.value === 'add') {
          // await companyApi.addCompany(formData.value);
          message.success('添加成功');
        } else {
          // await companyApi.updateCompany(formData.value);
          message.success('更新成功');
        }
        showModal.value = false;
        fetchCompanyData();
      } catch (error) {
        console.error('保存公司失败:', error);
        message.error('保存公司失败');
      }
    }
  });
};

// 处理选中行
const handleCheck = (keys) => {
  checkedRowKeys.value = keys;
};

// 处理页面变化
const handlePageChange = (page) => {
  pagination.page = page;
  fetchCompanyData();
};

// 处理删除确认
const handleDeleteConfirm = async () => {
  try {
    loading.value = true;
    await companyApi.deleteCompany(companyToDelete.value.company_id);
    message.success('删除成功');
    await fetchCompanyData();
  } catch (error) {
    console.error('删除公司失败:', error);
    message.error('删除公司失败');
  } finally {
    loading.value = false;
    showDeleteModal.value = false;
    companyToDelete.value = null;
  }
};

// 初始化
fetchCompanyData();
</script>

<style scoped>
.company-container {
  padding: 8px;
}
</style> 